<template>
  <div id="BrandRanking">
    <!-- 商品种类 -->
    <category_goods
      title="品牌分类"
      :showChild="false"
      v-model="checkedDatasJoe"
    />
    <!-- 时间 -->
    <section class>
      <!-- 时间 -->
      <time_options
        v-model="dateRank01"
        :radio_values="['日榜', '周榜', '月榜']"
        :timing="$global.timing"
        class="timeOptions"
        style="margin-right: 14px"
      />
      <div class="searchBox" id="livesearch">
        <el-input
          class="bor_left"
          v-model="keyWords"
          placeholder=" 请输入关键词在排行榜中搜索"
          @keyup.enter.native="Search"
        ></el-input>
        <div class="imgBox" @click="Search">
          <!-- <img src="@/assets/wang/talentCompare/search.png" /> -->
        </div>
      </div>
      <div class="btn_group">
        <button @click="generatorImage">
          <span></span>分享
        </button>
        <button @click="export_data">
          <span></span>导出
        </button>
      </div>
    </section>
    <ul
      key
      class="fixedThead"
      ref="fixedThead"
      :class="{ isShow: isFixed }"
      :style="showLeft == true ? 'left:222px' : 'left:98px'"
    >
      <li>排名</li>
      <li>品牌</li>
      <li tc>分类</li>
      <li
        tc
        v-if="orderType == 1 && sort != 1"
        style="  cursor: pointer;"
        @click="sort_fun(false, 1)"
      >
        关联视频
        <img
          src="@/assets/meng/down_up.png"
          class="sort"
          v-if="orderType == '1' && sort == '1'"
        />
        <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
      </li>
      <li tc v-if="orderType == 1 && sort == 1">
        关联视频
        <img src="@/assets/meng/down_up.png" v-if="orderType == 1 && sort == 1" class="sort" />
        <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
      </li>

      <li
        tc
        v-if="orderType == 1 && sort != 2"
        style="  cursor: pointer;"
        @click="sort_fun(false, 2)"
      >
        关联直播
        <img src="@/assets/meng/down_up.png" v-if="orderType == 1 && sort == 2" class="sort" />
        <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
      </li>
      <li tc v-if="orderType == 1 && sort == 2">
        关联直播
        <img src="@/assets/meng/down_up.png" v-if="orderType == 1 && sort == 2" class="sort" />
        <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
      </li>

      <li
        tc
        v-if="orderType == 1 && sort != 3"
        style="  cursor: pointer;"
        @click="sort_fun(false, 3)"
      >
        预估销量
        <img src="@/assets/meng/down_up.png" v-if="orderType == 1 && sort == 3" class="sort" />
        <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
      </li>
      <li tc v-if="orderType == 1 && sort == 3">
        预估销量
        <img src="@/assets/meng/down_up.png" v-if="orderType == 1 && sort == 3" class="sort" />
        <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
      </li>

      <li
        tc
        v-if="orderType == 1 && sort != 0"
        style="  cursor: pointer;"
        @click="sort_fun(false, 0)"
      >
        预估销售额
        <img src="@/assets/meng/down_up.png" v-if="orderType == 1 && sort == 0" class="sort" />
        <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
      </li>
      <li tc v-if="orderType == 1 && sort == 0">
        预估销售额
        <img src="@/assets/meng/down_up.png" v-if="orderType == 1 && sort == 0" class="sort" />
        <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
      </li>
      <li tc>操作</li>
    </ul>
    <table class="table" ref="capture01">
      <thead>
        <tr>
          <th>排名</th>
          <th>品牌</th>
          <th>分类</th>

          <th
            v-if="orderType == 1 && sort != 1"
            style="  cursor: pointer;"
            @click="sort_fun(false, 1)"
          >
            关联视频
            <img
              src="@/assets/meng/down_up.png"
              class="sort"
              v-if="orderType == '1' && sort == '1'"
            />
            <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
          </th>
          <th v-if="orderType == 1 && sort == 1">
            关联视频
            <img
              src="@/assets/meng/down_up.png"
              v-if="orderType == 1 && sort == 1"
              class="sort"
            />
            <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
          </th>

          <th
            v-if="orderType == 1 && sort != 2"
            style="  cursor: pointer;"
            @click="sort_fun(false, 2)"
          >
            关联直播
            <img
              src="@/assets/meng/down_up.png"
              v-if="orderType == 1 && sort == 2"
              class="sort"
            />
            <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
          </th>
          <th v-if="orderType == 1 && sort == 2">
            关联直播
            <img
              src="@/assets/meng/down_up.png"
              v-if="orderType == 1 && sort == 2"
              class="sort"
            />
            <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
          </th>

          <th
            v-if="orderType == 1 && sort != 3"
            style="  cursor: pointer;"
            @click="sort_fun(false, 3)"
          >
            预估销量
            <img
              src="@/assets/meng/down_up.png"
              v-if="orderType == 1 && sort == 3"
              class="sort"
            />
            <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
          </th>
          <th v-if="orderType == 1 && sort == 3">
            预估销量
            <img
              src="@/assets/meng/down_up.png"
              v-if="orderType == 1 && sort == 3"
              class="sort"
            />
            <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
          </th>

          <th
            v-if="orderType == 1 && sort != 0"
            style="  cursor: pointer;"
            @click="sort_fun(false, 0)"
          >
            预估销售额
            <img
              src="@/assets/meng/down_up.png"
              v-if="orderType == 1 && sort == 0"
              class="sort"
            />
            <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
          </th>
          <th v-if="orderType == 1 && sort == 0">
            预估销售额
            <img
              src="@/assets/meng/down_up.png"
              v-if="orderType == 1 && sort == 0"
              class="sort"
            />
            <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
          </th>

          <th>操作</th>
        </tr>
      </thead>
      <tbody v-if="brandArr.length != 0">
        <tr v-for="(item, index) in brandArr" :key="'a' + index" :id="!index ? 'tr1' : ''">
          <td>{{ 30 * (page - 1) + index + 1 }}</td>
          <td>
            <div class="telentName">
              <div class="logo_box" @click="BrandDetails(item.brandId)">
                <img :src="item.logo" v-if="item.logo" @error="item.logo = ''"/>
                <i v-else>{{item.brandName.slice(0,1)}}</i>
              </div>
              <p
                id="brand"
                style="cursor: pointer"
                @click="BrandDetails(item.brandId)"
              >{{ item.brandName }}</p>
            </div>
          </td>
          <td>
            <p>{{ item.categorys }}</p>
          </td>
          <td>{{ format_num(item.sellVideo) }}</td>
          <td>{{ format_num(item.sellLive) }}</td>
          <td>{{ format_num(item.salesVolume) }}</td>
          <td>{{ format_num(item.salesAmount) }}</td>
          <td>
            <div class="detailsBtnwl" @click="BrandDetails(item.brandId)">查看详情</div>
          </td>
        </tr>
      </tbody>
    </table>
    <div class="upgradeBox" v-if="!permissions">
      <RankUpgrade class="rankUpgrade" />
    </div>
    <!-- <p
      class="nothing"
      v-show="
        brandArr.length < 30 && !loading && permissions && brandArr.length != 0
      "
    >我是有底线的～</p> -->
    <div class="pageBox" v-if="brandArr.length != 0 || !permissions">
      <el-pagination
        background
        layout="prev, pager, next, jumper"
        :total="count"
        :page-size="30"
        :current-page="page"
        @current-change="toSearch"
        :hide-on-single-page="true"
      ></el-pagination>
    </div>
    <div
      v-loading="loading"
      v-if="loading"
      class="loading"
      element-loading-text="拼命加载中..."
      element-loading-spinner="el-icon-loading"
    ></div>

    <div
      class="empty"
      v-show="!loading && brandArr.length == 0 && permissions"
      style="height: 445px"
    >
      <img src="@/assets/liu/zw.png" />
      <p>暂无数据</p>
    </div>
  </div>
</template>

<script>
import RankUpgrade from '@/component/rankUpgrade.vue';
import category_goods from '@/component/category_goods';
import html2canvas from 'html2canvas';
export default {
  components: { RankUpgrade, category_goods },
  data() {
    return {
      checkedDatasJoe: {
        //商品类目数据初始数据，新筛选组件用
        parentId: 0,
        childIds: []
      },
      dateRank01: '日榜',
      keyWords: '',
      sort: 0,
      orderType: 1, //1降序 0升序
      brandArr: [],
      page: 1,
      count: 0,
      permissions: 1,
      loading: true,
      needBuy: true,
      busy: false,
      showLeft: true,
      isFixed: false,
      offsetTop: 0
    };
  },
  computed: {
  },
  watch: {
    checkedDatasJoe(){
      this.page = 1;
      this.brandArr = [];
      this.toSearch();
    },
    keyWords: function (newVal, oldVal) {
      if (newVal == '') {
        this.page = 1;
        this.brandArr = [];
        this.toSearch();
      }
    },

    dateRank01: function (newVal, oldVal) {
      this.page = 1;
      this.brandArr = [];
      this.toSearch();
    },
    '$store.state.left_nav_flag'(old, newOld) {
      this.showLeft = newOld;
      if ((newOld = false)) {
        this.setTBBar();
      } else {
        this.setTBBar();
      }
    }
  },
  mounted() {
    window.addEventListener('scroll', this.initHeight);
    window.addEventListener('resize', () => {
      //给浏览器窗口绑定变化大小事件
      this.setTBBar();
    });
  },
  created() {
    if (this.$route.params.index) {
      this.dateRank01 = this.$route.params.index;
    }
  },
  methods: {
    // 获取子节点函数（后期可集成到一个库里）
    getChilds(pNode) {
      if (!pNode) return false;
      let nodes = pNode.childNodes;
      let newList = [];
      for (let i = 0; i < nodes.length; i++) {
        let node = nodes[i];
        if (node.nodeType === 1) {
          //判断类型
          newList.push(node);
        }
      }
      return newList;
    },
    // 设置表格表头滑动置顶
    setTBBar() {
      this.$nextTick(() => {
        let tableEl = this.$refs.tableEl;
        let ulEl = this.$refs.fixedThead;
        let tr1 = document.querySelector('#tr1');
        // thTrEl.style.width = tableEl.offsetWidth+'px';
        if (tr1) {
          let tds = this.getChilds(tr1);
          let liEls = this.getChilds(ulEl);

          for (let i = 0; i < liEls.length; i++) {
            liEls[i].style.width = tds[i].offsetWidth + 'px';
          }
        }
      });
    },
    // 排序
    sort_fun(parm01, parm02) {
      if (parm01) {
        this.orderType = 0;
      } else {
        this.orderType = 1;
      }
      this.sort = parm02;
      this.page = 1;
      this.brandArr = [];
      this.toSearch();
    },
    //搜索
    Search() {
      this.brandArr = [];
      this.page = 1;
      this.toSearch();
    },

    toSearch(cpage) {
      this.loading = true;
      this.needBuy = true;
      this.brandArr = [];
      this.permissions = 1;
      if (cpage) {
        this.page = cpage;
        this.backTop();
        //console.log("page", this.page);
      }
      // 榜单类型 1日榜 2周榜 3月榜
      let startDate = '';
      let endDate = '';

      if (this.dateRank01.split('?')[0] == '日榜') {
        startDate = this.dateRank01.split('?')[1];
        endDate = this.dateRank01.split('?')[1];
      } else if (this.dateRank01.split('?')[0] == '周榜') {
        startDate = this.dateRank01.split('?')[1].substring(0, 10);
        endDate = this.dateRank01.split('?')[1].substring(11, 22);
      } else if (this.dateRank01.split('?')[0] == '月榜') {
        startDate = this.dateRank01.split('?')[1].substring(0, 10);
        endDate = this.dateRank01.split('?')[1].substring(11, 22);
      }
      //品牌榜单
      this.$axios
        .post('api/Brand/BrandRank', {
          BrandName: this.keyWords,
          CategoryId: this.checkedDatasJoe.parentId,
          categoryIds: this.checkedDatasJoe.childIds,
          startDate: startDate,
          endDate: endDate,
          page: this.page,
          size: 30,
          orderType: this.orderType,
          orderValue: this.sort
        })
        .then(res => {
          this.loading = false;
          if (res.data.code1 ==1013||res.data.code == 1003||res.data.code ==1013) {
            this.permissions = 0;
            this.table_data01 = [];
          } else {
            this.permissions = 1;
          }
          if (res.data.code == 0) {
            this.brandArr = res.data.data;

            if(res.data.count>3000){
              this.count = 3000
            }else {
              this.count = res.data.count;
            }
          }
          this.setTBBar();
        })
        .catch(err => {
          console.log(err);
        });
    },
    loadMore() {
      this.toSearch();
    },
    backTop() {
      document.body.scrollTop = document.documentElement.scrollTop = 0;
    },
    BrandDetails(id) {
      let routeUrl = this.$router.resolve({
        path: '/talent_main/brandRoot',
        query: { id }
      });
      window.open(routeUrl.href, '_blank');
    },

    // 导出
    generatorImage() {
      var that = this;
      const loading = this.$loading({
        lock: true,
        text: '导出中...',
        spinner: 'el-icon-loading',
        customClass: 'customClass'
      });
      var shareContent;
      shareContent = this.$refs.capture01; //需要截图的包裹的（原生的）DOM 对象
      var width = shareContent.offsetWidth; //获取dom 宽度
      var height = shareContent.offsetHeight; //获取dom 高度
      var canvas = document.createElement('canvas'); //创建一个canvas节点
      //   var scale = window.devicePixelRatio //定义任意放大倍数 支持小数 //   var scale = 2 //定义任意放大倍数 支持小数
      var scale = 1;
      canvas.width = width * scale * scale; //定义canvas 宽度 * 缩放
      canvas.height = height * scale * scale; //定义canvas高度 *缩放
      canvas.style.width = width + 'px';
      canvas.style.height = height + 'px';
      canvas.getContext('2d').scale(scale, scale); //获取context,设置scale
      var opts = {
        dpi: window.devicePixelRatio,
        scale: scale, // 添加的scale 参数
        useCORS: true,
        canvas: canvas, //自定义 canvas
        logging: true //日志开关
      };
      html2canvas(shareContent, opts).then(canvas => {
        let str;

        str = `《品牌排行榜-${this.timestamp(
          new Date().getTime() / 1000,
          'Y年M月D日'
        )}》.png`;

        canvas.toBlob(
          function (blob) {
            const eleLink = document.createElement('a');
            eleLink.download = str;
            eleLink.style.display = 'none';
            // 字符内容转变成blob地址
            eleLink.href = URL.createObjectURL(blob);
            // 触发点击
            document.body.appendChild(eleLink);
            eleLink.click();
            // 然后移除
            document.body.removeChild(eleLink);
          },
          'image/png',
          1
        );
        loading.close();
      });
    },
    // 文字加replace 数字加\t
    export_data() {
      let that = this;
      let str = '';

      str = `排名,品牌,分类,关联视频,关联直播,预估销量,预估销售额\n`;

      for (let i = 0; i < that.brandArr.length; i++) {
        str += `${i + 1},${that.brandArr[i].brandName},${that.brandArr[i].categorys.replace(
          /,/g,
          '、'
        )},${that.brandArr[i].sellVideo},${that.brandArr[i].sellLive},${
          that.brandArr[i].salesVolume
        },${that.brandArr[i].salesAmount}\n`;
      }
      var blob = new Blob([str], { type: 'text/plain;charset=utf-8' }); //解决中文乱码问题
      blob = new Blob([String.fromCharCode(0xfeff), blob], { type: blob.type });
      let object_url = window.URL.createObjectURL(blob);
      var link = document.createElement('a');
      link.href = object_url;
      let str_name = '';
      str_name = `《品牌排行榜-${this.timestamp(
          new Date().getTime() / 1000,
          'Y年M月D日'
        )}》.csv`;
      link.download = str_name;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    initHeight() {
      var scrollTop =
        window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      this.isFixed = scrollTop > 220 ? true : false;
    }
  },
  destroyed(){
    window.removeEventListener("scroll", this.initHeight);
  }
};
</script>
<style lang="less" scopd>
#BrandRanking {
  width: 100%;
  height: 100%;
  padding: 20px 0 0;
  .timeOptions {
    display: inline-block;
    float: left;
  }
  // 搜索框
  .searchBox {
    width: 308px;
    height: 32px;
    border-radius: 4px;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1px solid #e5e5e5;
    float: left;
    .el-input__inner {
      flex: 1;
    }
    .imgBox:hover {
      background: url('../../../assets/wang/talentCompare/search.png') no-repeat 10px 7px, #fff;
      background-size: 15px 15px;
    }
    .imgBox {
      width: 40px;
      height: 32px;
      border-radius: 0px 4px 4px 0px;
      cursor: pointer;
      display: grid;
      place-items: center;
      background: url('../../../assets/wang/talentCompare/search-nohover.png') no-repeat 10px 7px,
        #fff;
      background-size: 15px 15px;
      img {
        width: 15px;
        height: 15px;
      }
    }
  }
  .btn_group {
    margin-bottom: 14px;
    text-align: right;
    button {
      width: 70px;
      height: 32px;
      border-radius: 4px;
      border: solid 1px #e5e5e5;
      font-size: 14px;
      // line-height: 30px;
      box-sizing: border-box;
      color: #555;
      text-align: center;
    }
    button:nth-of-type(2) {
      color: #67ac5b;
      border: 1px solid #67ac5b;
    }
    > button:nth-child(1) {
      margin-right: 10px;
      span {
        display: inline-block;
        width: 14px;
        height: 14px;
        background: url('../../../assets/zhao/fenx.png') no-repeat;
        background-size: 100% 100%;
        margin-right: 4px;
        position: relative;
        top: 2px;
      }
    }
    > button:nth-child(2) {
      span {
        display: inline-block;
        width: 14px;
        height: 14px;
        background: url('../../../assets/zhao/daoc.png') no-repeat;
        background-size: 100% 100%;
        margin-right: 4px;
        position: relative;
        top: 2px;
      }
    }
    button:nth-of-type(1):hover {
      color: #777;
      span {
        background: url('../../../assets/zhao/fenx_h.png') no-repeat;
        background-size: 100% 100%;
      }
    }
    button:nth-of-type(2):hover {
      color: #80be76;
      border-color: #80be76;
      span {
        background: url('../../../assets/zhao/daoc_h.png') no-repeat;
        background-size: 100% 100%;
      }
    }
  }

  .table {
    margin-top: 14px;
    text-align: center;
    box-sizing: border-box;
    thead {
      th {
        padding: 0 5px;
        .sort {
          width: 4px;
          height: 10px;
          margin-right: 2px;
        }
      }
      th:nth-child(1) {
        text-align: left;
        padding-left: 55px;
      }
      th:nth-child(3),
      th:nth-child(5) {
        width: 12%;
      }
      th:nth-child(2) {
        text-align: left;
      }
    }
  }
  tbody {
    tr {
      height: 78px;

      td:nth-child(1) {
        font-family: DINAlternate-Bold;
        font-size: 15px;
        width: 15%;
        text-align: left;
        padding-left: 63px;
      }
      td:nth-child(2) {
        .telentName {
          text-align: left;
          display: flex;
          align-items: center;
          p:nth-of-type(1) {
            max-width: 250px;
            font-size: 14px;
            color: #222;
            font-weight: 600;
            cursor: pointer;
            white-space:nowrap;//不换行
            overflow: hidden;//超出隐藏
            text-overflow: ellipsis;//变成...
          }
          p:nth-of-type(1):hover {
            color: #ff924b;
          }
          .logo_box{
            width: 50px;
            height: 50px;
            border-radius: 50%;
            overflow: hidden;
            margin-right: 15px;
            flex-shrink: 0;
            img{
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
            i{
              width: 100%;
              height: 100%;
              color: #ffa500;
              background-color: #fff1e8;
              display: flex;
              justify-content: center;
              align-items: center;
              font-style: normal;
              font-size: 20px;
              cursor: pointer;
            }
          }
          img {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            cursor: pointer;
            object-fit: cover;
          }
        }
      }
      td:nth-child(3) {
        font-size: 14px;
        letter-spacing: 0px;
        color: #222222;
      }
      td:nth-child(4),
      td:nth-child(5),
      td:nth-child(6),
      td:nth-child(7) {
        font-family: DINAlternate-Bold;
        font-size: 15px;
        color: #222;
      }
    }
    img {
      width: 8px;
      height: 12px;
    }
  }
  .paginationBox {
    width: 100%;
    background-color: #fff;
    // margin-top: 10px;
    overflow: hidden;
    padding: 20px;
    box-sizing: border-box;
    // padding-left: 1000px;
    .el-pagination {
      float: right;
    }
  }
  .detailsBtnwl:hover {
    color: #ff924b;
    border-color: #ff924b;
  } // 升级会员
  .upgradeBox {
    min-height: 60vh;
    position: relative;
    .rankUpgrade {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }
}
.fixedThead {
  display: none;
  position: fixed;
  top: 60px;
  left: 200px;

  border-radius: 4px;
  font-size: 14px;
  font-weight: 600;
  color: #555;
  background-color: #f5f9ff;
  height: 48px;
  line-height: 48px;
  overflow: hidden;
  z-index: 99;
  font-size: 0;
  li {
    box-sizing: border-box;
    display: inline-block;
    font-size: 14px;
  }

  li:nth-child(2) {
    padding-left: 9px;
  }
  img {
    width: 5px;
    height: 10px;
    margin-right: 2px;
    vertical-align: 0px;
  }
  &.isShow {
    display: block;
  }
}
[tc] {
  text-align: center;
}
[tl] {
  text-align: left;
}
[tr] {
  text-align: right;
}
</style>
